// 15.三数之和
package Leetcode_Second_Brush;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution015 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();

        Arrays.sort(nums);

        for (int first = 0; first < nums.length; first++) {
            if (first > 0 && nums[first] == nums[first - 1])
                continue;
            int second = first + 1;
            int third = nums.length - 1;
            while (second < third) {
                if (nums[second] + nums[third] < -nums[first])
                    second++;
                else if (nums[second] + nums[third] > -nums[first])
                    third--;
                else {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[first]);
                    list.add(nums[second]);
                    list.add(nums[third]);
                    result.add(list);
                    do {
                        second++;
                    } while (second < third && nums[second - 1] == nums[second]);
                }
            }
        }

        return result;
    }
}
